package com.bincloud.vue.admin.common.util;

import javax.servlet.http.HttpServletRequest;

/**
 * IP 工具类
 * @author bincloud, mvpzhou
 */
@SuppressWarnings("unused")
public class IpUtils {

    private static final String UNKNOWN = "unknown";

    private IpUtils(){}

    public static String getIpAddress(HttpServletRequest request) {
        if (request == null) {
            return UNKNOWN;
        }
        String ip = request.getHeader("x-forwarded-for");
        if (isEmptyIP(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isEmptyIP(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (isEmptyIP(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isEmptyIP(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (isEmptyIP(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    private static boolean isEmptyIP(final String ip) {
        return ip == null || ip.length() == 0 || ip.trim().equals("") || UNKNOWN.equalsIgnoreCase(ip);
    }
}
